import { useEffect, useRef, useState } from 'react';

const useCountdown = (time: number = 60) => {
  let [countdown, setCountdown] = useState<number>(time);
  const [start, setStart] = useState<boolean>(false);
  let timeId = useRef<NodeJS.Timeout>();
  const subCountdown = ()=> {
    setStart(true);
    clearInterval(timeId.current);
    timeId.current = setInterval(()=> {
      setCountdown(countdown -= 1);
      if (countdown <= 0) {
        clearInterval(timeId.current);
        setStart(false);
        setCountdown(time);
      }
    }, 1000);
  };
  useEffect(() => {
    return () => {
      clearInterval(timeId.current);
    };
  }, []);
  return {
    countdown,
    start,
    subCountdown,
  };
};

export default useCountdown;
